/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client;

import java.util.ArrayList;
import java.util.List;
import static client.RefManager.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author zero.one
 */
public class NachrichtSendenThread extends Thread {

    String nachricht;

    public NachrichtSendenThread(String nachricht) {
        this.nachricht = nachricht;
    }

    public void run() {

        DatagramSocket clientSocket;
        try {
            clientSocket = new DatagramSocket();
        } catch (SocketException ex) {
            System.err.println("UDP-Thread konnte kein Socket erstellen");
            return;
        }


        for (Entry<String, String> user : client.userMap.entrySet()) {
            try {
                InetAddress userIP = InetAddress.getByName(user.getKey());
                String userName = user.getValue();
                
                String userPlusNachricht = thread.getUsername() + ": " + nachricht+ "\n";
                

                try {
                    /* String in Byte-Array umwandeln */
                    byte[] sendData = userPlusNachricht.getBytes("UTF-8");
                    /* Paket erzeugen */
                    DatagramPacket sendPacket =
                            new DatagramPacket(
                            sendData,
                            sendData.length,
                            userIP,
                            50001);
                    /* Senden des Pakets */
                    clientSocket.send(sendPacket);
                } catch (IOException e) {
                    System.err.println(e.toString());
                }
                System.out.println("UDP Client has sent the message: " + nachricht);
            } catch (UnknownHostException ex) {
                System.err.println(ex.toString());
            }
        }
        clientSocket.close();
    }
}
